//
//  MainMenuController.m
//  ServiceApp
//
//  Created by User-23 on 12/15/14.
//  Copyright (c) 2014 TrainingCamp. All rights reserved.
//

#import "MainMenuController.h"
#import "Menu.h"
#import "SubCategory.h"
#import "SubCategoryMenuController.h"
@interface MainMenuController ()

@property Menu *menu;

@end

static NSString *kMenuURL = @"http://78.90.20.186:8080/ProjectRestaurant/menu";

@implementation MainMenuController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"Menu";
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(update:)
                                                 name:@"MenuUpdate" object:nil];
    self.menu = [[Menu alloc] init];
    [self loadMenu];
}

#pragma mark - Table View Data Source Methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [self.menu count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BasicCell" forIndexPath:indexPath];
    
    // Configure the cell...
    cell.textLabel.text = [self.menu categoryAtIndex:indexPath.row].name; //[self.menu.categories[indexPath.row] name];
    cell.tag = [self.menu categoryAtIndex:indexPath.row].categoryId;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self performSegueWithIdentifier:@"MenuToSubCategory" sender:[self.tableView cellForRowAtIndexPath:indexPath]];
}

#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    SubCategoryMenuController* vc = [segue destinationViewController];
    vc.selecetedSubCategoryId = [sender tag];
    vc.title = [sender textLabel].text;
}

#pragma mark - Networking

- (void) update:(NSNotification*) note{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
    });
}

- (void) loadMenu{
    NSURLSession* session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:kMenuURL]];
    
    NSURLSessionDataTask* downloadJSONTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSError* mistake = nil;
        
        NSMutableDictionary* jsonDictonary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&mistake];
        NSArray *categories = jsonDictonary[@"categories"];
        
        if (mistake != nil) {
            NSLog(@"Error : %@", [mistake localizedDescription]);
        }
        else {
            for (NSDictionary* category in categories) {
                SubCategory *subCat = [[SubCategory alloc] init];
                subCat.name = category[@"name"];
                subCat.categoryId = [category[@"categoryId"] integerValue];
                [self.menu addSubCategory:subCat];
            }
            [[NSNotificationCenter defaultCenter] postNotificationName:@"MenuUpdate" object:self userInfo:nil];
        }
        
        
    }];
    [downloadJSONTask resume];
}

@end
